#include "common.h"
#include "syscall.h"
#include "fs.h"
#include "memory.h"
_RegSet* do_syscall(_RegSet *r) {
    uintptr_t a[4];
    a[0] = SYSCALL_ARG1(r);
    a[1] = SYSCALL_ARG2(r);
    a[2] = SYSCALL_ARG3(r);
    a[3] = SYSCALL_ARG4(r);
    switch (a[0]) {
        case SYS_none:
            r->eax = 1;
            break;
        case SYS_exit:
            _halt(a[1]);
            break;
        case SYS_write:
        {            
            ssize_t ret = fs_write(a[1], (void *)a[2], a[3]);
            r->eax = ret;
            break;
        }
        case SYS_brk:
            r->eax = fs_brk(a[1]);
            break;
        case SYS_open: 
        {
            const char *path = (const char*)a[1];
            int fd;
            fd = fs_open(path, a[2], a[3]);
            r->eax = fd;
            break;
        }
        case SYS_read: 
        {
            ssize_t ret;
            ret = fs_read(a[1], (void*)a[2], a[3]);
            r->eax = ret;
            break;
        }
        case SYS_close: 
        {
            int ret;
            ret = fs_close(a[1]);
            r->eax = ret;
            break;
        }
        case SYS_lseek: 
        {
            off_t ret;
            ret = fs_lseek(a[1], a[2], a[3]);
            r->eax = ret;
            break;
        }    
        default: 
            panic("Unhandled syscall ID = %d", a[0]);
    }
    return NULL;
}
